package idc.nlp.ok.protocol.speaker.spi.constitparser;

import idc.nlp.ok.model.Role;
import idc.nlp.ok.model.Speaker;
import idc.nlp.ok.protocol.speaker.parser.SpeakerParser;
import idc.nlp.ok.protocol.speaker.parser.common.SpeakerParserUtils;
import il.ac.idc.nlp.constit.ConstitTreeMaker;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import edu.berkeley.nlp.syntax.Tree;

public class SpeakerConstitParser implements SpeakerParser {

	public static final String NAME = "CONSTITUTE";

	private ConstitTreeMaker treeMaker;

	public String getParseMethodName() {
		return NAME;
	}

	public void init() throws IOException {
		treeMaker = new ConstitTreeMaker(ConstitTreeMaker.class.getResourceAsStream("/full_nodef.twcount"),
				ConstitTreeMaker.class.getResourceAsStream("lexicon.utf8.sqlite"));
	}

	public Speaker parse(String speakerLine) {
		Speaker speaker = SpeakerParserUtils.parseAnonymous(speakerLine);
		if (speaker != null)
			return speaker;
		speaker = SpeakerParserUtils.parseMK(speakerLine);
		if (speaker != null)
			return speaker;
		speaker = parseImpl(speakerLine);
		return speaker;
	}

	private Speaker parseImpl(String speakerLine) {
		Tree<String> tree;
		try {
			tree = treeMaker.parse(speakerLine);
			ConstitTreeMaker.cleanTree(tree);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		while (tree.getChildren().size() == 1) {
			tree = tree.getChild(0);
		}
		List<Tree<String>> children = tree.getChildren();
		if (children.size() != 3) {
			return null;
		}
		Tree<String> nameChild = children.get(1); // Rule Name yyCOL

		List<String> nameTerminals = nameChild.getTerminalYield();
		if (nameTerminals.isEmpty())
			return null;

		String firstName = nameTerminals.get(0);
		String name = firstName + StringUtils.substringAfterLast(speakerLine, firstName);
		name = StringUtils.left(name, name.length() - 1);
		name = StringUtils.trim(name);
		String ruleName = StringUtils.substringBeforeLast(speakerLine, firstName);
		ruleName = StringUtils.trim(ruleName);

		Speaker speaker = new Speaker(speakerLine, name);
		speaker.setSource(speakerLine);
		Role rule = new Role(ruleName);
		speaker.setRole(rule);
		return speaker;
	}

}
